<template>
  <div class="flex h-screen bg-gray-900 text-white overflow-hidden">
    <!-- 侧边栏 - 聊天历史 -->
    <div class="w-64 bg-gray-800 border-r border-gray-700 flex flex-col">
      <!-- 新建聊天按钮 -->
      <div class="p-4">
        <button 
          @click="showNewChatDialog = true" 
          class="w-full flex items-center justify-center gap-2 bg-primary-500 hover:bg-primary-600 text-white py-2 px-4 rounded-lg transition-colors"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
          </svg>
          新建聊天
        </button>
      </div>
      
      <!-- 聊天历史列表 -->
      <div class="flex-1 overflow-y-auto">
        <div v-if="chatHistory.length === 0" class="text-center text-gray-400 p-4">
          暂无聊天记录
        </div>
        <div 
          v-for="(chat, index) in chatHistory" 
          :key="index"
          @click="selectChat(chat.id)"
          class="p-3 hover:bg-gray-700 cursor-pointer transition-colors"
          :class="{'bg-gray-700': currentChatId === chat.id}"
        >
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2 truncate">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zM9 9h2v2H9V9z" clip-rule="evenodd" />
              </svg>
              <span class="truncate">{{ chat.title }}</span>
            </div>
            <button 
              @click.stop="openEditChatDialog(chat)" 
              class="text-gray-400 hover:text-gray-200"
            >
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
              </svg>
            </button>
            <button 
              @click.stop="deleteChat(chat.id)" 
              class="text-gray-400 hover:text-gray-200"
            >
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
              </svg>
            </button>
          </div>
          <div class="text-xs text-gray-400 mt-1 truncate">
            {{ chat.lastMessage || '无消息' }}
          </div>
        </div>
      </div>
      
      <!-- 用户信息 -->
      <div class="p-4 border-t border-gray-700 flex items-center">
        <div class="w-8 h-8 rounded-full bg-primary-500 flex items-center justify-center text-white font-bold">
          U
        </div>
        <div class="ml-2">
          <div class="text-sm font-medium">用户</div>
          <div class="text-xs text-gray-400">免费版</div>
        </div>
      </div>
    </div>
    
    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col">
      <!-- 聊天头部 -->
      <div class="p-4 border-b border-gray-700 flex items-center justify-between">
        <h1 class="text-xl font-bold">{{ currentChat?.title || '新的对话' }}</h1>
        <div class="flex items-center gap-4">
          <button class="text-gray-400 hover:text-white">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
              <path d="M8 9a3 3 0 100-6 3 3 0 000 6zM8 11a6 6 0 016 6H2a6 6 0 016-6zM16 7a1 1 0 10-2 0v1h-1a1 1 0 100 2h1v1a1 1 0 102 0v-1h1a1 1 0 100-2h-1V7z" />
            </svg>
          </button>
          <button class="text-gray-400 hover:text-white">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd" />
            </svg>
          </button>
        </div>
      </div>
      
      <!-- 消息列表 -->
      <div class="flex-1 overflow-y-auto p-4 space-y-6" ref="messagesContainer">
        <div v-if="currentChat?.messages.length === 0" class="flex flex-col items-center justify-center h-full text-gray-400">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
          </svg>
          <p class="text-xl">开始一个新的对话</p>
          <p class="mt-2">输入您的问题，AI将为您提供答案</p>
        </div>
        
        <template v-for="(message, index) in currentChat?.messages" :key="index">
          <!-- 用户消息 -->
          <div v-if="message.role === 'user'" class="flex items-start gap-4">
            <div class="w-8 h-8 rounded-full bg-primary-500 flex items-center justify-center text-white font-bold flex-shrink-0">
              U
            </div>
            <div class="flex-1">
              <div class="bg-gray-800 rounded-lg p-4">
                <p class="whitespace-pre-wrap">{{ message.content }}</p>
              </div>
              <div class="flex items-center mt-2 text-xs text-gray-400">
                {{ formatTime(message.timestamp) }}
              </div>
            </div>
          </div>
          
          <!-- AI消息 -->
          <div v-else class="flex items-start gap-4">
            <div class="w-8 h-8 rounded-full bg-quaternary-500 flex items-center justify-center text-white font-bold flex-shrink-0">
              AI
            </div>
            <div class="flex-1">
              <div class="bg-gray-800 rounded-lg p-4">
                <p class="whitespace-pre-wrap">{{ message.content }}</p>
              </div>
              <div class="flex items-center gap-4 mt-2 text-xs text-gray-400">
                {{ formatTime(message.timestamp) }}
                <div class="flex items-center gap-2">
                  <button class="hover:text-white">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                      <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                      <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" />
                    </svg>
                  </button>
                  <button class="hover:text-white">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                      <path d="M15 8a3 3 0 10-2.977-2.63l-4.94 2.47a3 3 0 100 4.319l4.94 2.47a3 3 0 10.895-1.789l-4.94-2.47a3.027 3.027 0 000-.74l4.94-2.47C13.456 7.68 14.19 8 15 8z" />
                    </svg>
                  </button>
                  <button class="hover:text-white">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                      <path d="M7 9a2 2 0 012-2h6a2 2 0 012 2v6a2 2 0 01-2 2H9a2 2 0 01-2-2V9z" />
                      <path d="M5 3a2 2 0 00-2 2v6a2 2 0 002 2V5h8a2 2 0 00-2-2H5z" />
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </template>
        
        <!-- 加载中状态 -->
        <div v-if="isLoading" class="flex items-start gap-4">
          <div class="w-8 h-8 rounded-full bg-quaternary-500 flex items-center justify-center text-white font-bold flex-shrink-0">
            AI
          </div>
          <div class="flex-1">
            <div class="bg-gray-800 rounded-lg p-4">
              <div class="flex space-x-2">
                <div class="w-2 h-2 rounded-full bg-gray-400 animate-pulse"></div>
                <div class="w-2 h-2 rounded-full bg-gray-400 animate-pulse" style="animation-delay: 0.2s"></div>
                <div class="w-2 h-2 rounded-full bg-gray-400 animate-pulse" style="animation-delay: 0.4s"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="p-4 border-t border-gray-700">
        <div class="relative">
          <textarea 
            v-model="userInput" 
            @keydown.enter.prevent="handleSendMessage"
            placeholder="输入您的问题..." 
            class="w-full bg-gray-800 text-white rounded-lg pl-4 pr-12 py-3 resize-none focus:outline-none focus:ring-2 focus:ring-primary-500"
            rows="3"
          ></textarea>
          <button 
            @click="handleSendMessage" 
            class="absolute right-3 bottom-3 text-white bg-primary-500 hover:bg-primary-600 rounded-lg p-2 transition-colors"
            :disabled="!userInput.trim() || isLoading"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
              <path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z" />
            </svg>
          </button>
        </div>
        <div class="flex justify-between items-center mt-2 text-xs text-gray-400">
          <div>支持 Markdown 格式</div>
          <div>Shift + Enter 换行</div>
        </div>
      </div>
    </div>
    
    <!-- 新建对话弹窗 -->
    <div v-if="showNewChatDialog" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
        <h2 class="text-xl font-bold mb-4">新建对话</h2>
        <input 
          v-model="newChatTitle" 
          type="text" 
          placeholder="输入对话名称" 
          class="w-full bg-gray-700 text-white rounded-lg px-4 py-2 mb-4 focus:outline-none focus:ring-2 focus:ring-primary-500"
          @keydown.enter="confirmCreateNewChat"
        />
        <div class="flex justify-end gap-3">
          <button 
            @click="showNewChatDialog = false" 
            class="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
          >
            取消
          </button>
          <button 
            @click="confirmCreateNewChat" 
            class="px-4 py-2 bg-primary-500 hover:bg-primary-600 text-white rounded-lg transition-colors"
          >
            创建
          </button>
        </div>
      </div>
    </div>
    
    <!-- 编辑对话弹窗 -->
    <div v-if="showEditChatDialog" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
        <h2 class="text-xl font-bold mb-4">编辑对话</h2>
        <input 
          v-model="editChatTitle" 
          type="text" 
          placeholder="输入对话名称" 
          class="w-full bg-gray-700 text-white rounded-lg px-4 py-2 mb-4 focus:outline-none focus:ring-2 focus:ring-primary-500"
          @keydown.enter="confirmEditChat"
        />
        <div class="flex justify-end gap-3">
          <button 
            @click="showEditChatDialog = false" 
            class="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
          >
            取消
          </button>
          <button 
            @click="confirmEditChat" 
            class="px-4 py-2 bg-primary-500 hover:bg-primary-600 text-white rounded-lg transition-colors"
          >
            保存
          </button>
        </div>
      </div>
    </div>
    
    <!-- 登录提示弹窗 -->
    <div v-if="showLoginDialog" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md transform transition-all duration-300 scale-100 opacity-100">
        <div class="text-center mb-6">
          <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary-500/20 mb-4">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-primary-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          </div>
          <h2 class="text-xl font-bold text-white">需要登录</h2>
          <p class="text-gray-300 mt-2">请登录后继续使用AI对话功能</p>
        </div>
        
        <div class="space-y-4">
          <button 
            @click="goToLogin" 
            class="w-full bg-primary-500 hover:bg-primary-600 text-white py-3 px-4 rounded-lg transition-colors flex items-center justify-center"
          >
            <span>立即登录</span>
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 ml-2" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L12.586 11H5a1 1 0 110-2h7.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd" />
            </svg>
          </button>
          
          <button 
            @click="showLoginDialog = false" 
            class="w-full bg-gray-700 hover:bg-gray-600 text-white py-3 px-4 rounded-lg transition-colors"
          >
            稍后再说
          </button>
        </div>
        
        <div class="mt-6 text-center text-sm text-gray-400">
          <p>还没有账号？<a href="#" class="text-primary-400 hover:text-primary-300">立即注册</a></p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

interface Message {
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
}

interface Chat {
  id: string;
  title: string;
  messages: Message[];
  lastMessage?: string;
  createdAt: number;
}

// 状态
const userInput = ref('');
const isLoading = ref(false);
const messagesContainer = ref<HTMLElement | null>(null);
const chatHistory = ref<Chat[]>([]);
const currentChatId = ref<string | null>(null);
const route = useRoute();
const router = useRouter();

// 新增：弹窗相关状态
const showNewChatDialog = ref(false);
const newChatTitle = ref('新的对话');
const showEditChatDialog = ref(false);
const editChatTitle = ref('');
const editingChatId = ref<string | null>(null);

// 新增：登录相关状态
const isLoggedIn = ref(false); // 实际项目中应该从用户状态或token中获取
const showLoginDialog = ref(false);

// 计算当前聊天
const currentChat = computed(() => {
  return chatHistory.value.find(chat => chat.id === currentChatId.value) || null;
});

// 初始化
onMounted(() => {
  // 从本地存储加载聊天历史
  const savedHistory = localStorage.getItem('chatHistory');
  if (savedHistory) {
    chatHistory.value = JSON.parse(savedHistory);
  }
  
  // 如果URL中有聊天ID，则选择该聊天
  const chatId = route.params.id as string;
  if (chatId && chatHistory.value.some(chat => chat.id === chatId)) {
    currentChatId.value = chatId;
  } else if (chatHistory.value.length > 0) {
    // 否则选择最新的聊天
    currentChatId.value = chatHistory.value[0].id;
  } else {
    // 如果没有聊天历史，创建一个新聊天
    showNewChatDialog.value = true;
  }
});

// 监听聊天历史变化，保存到本地存储
watch(chatHistory, () => {
  localStorage.setItem('chatHistory', JSON.stringify(chatHistory.value));
}, { deep: true });

// 监听消息变化，滚动到底部
watch(() => currentChat.value?.messages.length, () => {
  scrollToBottom();
});

// 新增：确认创建新聊天
const confirmCreateNewChat = () => {
  createNewChat(newChatTitle.value);
  showNewChatDialog.value = false;
  newChatTitle.value = '新的对话';
};

// 修改：创建新聊天
const createNewChat = (title: string = '新的对话') => {
  const newChat: Chat = {
    id: generateId(),
    title: title,
    messages: [],
    createdAt: Date.now()
  };
  
  chatHistory.value.unshift(newChat);
  currentChatId.value = newChat.id;
  router.push(`/chat/${newChat.id}`);
};

// 选择聊天
const selectChat = (chatId: string) => {
  currentChatId.value = chatId;
  router.push(`/chat/${chatId}`);
};

// 删除聊天
const deleteChat = (chatId: string) => {
  const index = chatHistory.value.findIndex(chat => chat.id === chatId);
  if (index !== -1) {
    chatHistory.value.splice(index, 1);
    
    // 如果删除的是当前聊天，则选择另一个聊天
    if (currentChatId.value === chatId) {
      if (chatHistory.value.length > 0) {
        currentChatId.value = chatHistory.value[0].id;
        router.push(`/chat/${currentChatId.value}`);
      } else {
        showNewChatDialog.value = true;
      }
    }
  }
};

// 新增：打开编辑对话弹窗
const openEditChatDialog = (chat: Chat) => {
  editingChatId.value = chat.id;
  editChatTitle.value = chat.title;
  showEditChatDialog.value = true;
};

// 新增：确认编辑对话
const confirmEditChat = () => {
  if (editingChatId.value) {
    const chat = chatHistory.value.find(chat => chat.id === editingChatId.value);
    if (chat) {
      chat.title = editChatTitle.value;
    }
  }
  showEditChatDialog.value = false;
  editingChatId.value = null;
};

// 新增：处理发送消息前的登录检查
const handleSendMessage = () => {
  if (!isLoggedIn.value) {
    showLoginDialog.value = true;
    return;
  }
  sendMessage();
};

// 新增：跳转到登录页面
const goToLogin = () => {
  showLoginDialog.value = false;
  // 实际项目中应该跳转到登录页面
  router.push('/login');
};

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return;
  
  // 确保有当前聊天
  if (!currentChatId.value) {
    createNewChat();
  }
  
  const chat = chatHistory.value.find(chat => chat.id === currentChatId.value);
  if (!chat) return;
  
  // 添加用户消息
  const userMessage: Message = {
    role: 'user',
    content: userInput.value.trim(),
    timestamp: Date.now()
  };
  
  chat.messages.push(userMessage);
  
  // 如果是第一条消息，更新聊天标题
  if (chat.messages.length === 1) {
    chat.title = userInput.value.trim().substring(0, 30) + (userInput.value.trim().length > 30 ? '...' : '');
  }
  
  // 更新最后一条消息
  chat.lastMessage = userInput.value.trim();
  
  // 清空输入框
  userInput.value = '';
  
  // 模拟AI响应
  isLoading.value = true;
  
  try {
    // 这里应该调用实际的AI API
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟AI响应
    const aiResponse: Message = {
      role: 'assistant',
      content: generateAIResponse(userMessage.content),
      timestamp: Date.now()
    };
    
    chat.messages.push(aiResponse);
  } catch (error) {
    console.error('获取AI响应失败', error);
    
    // 添加错误消息
    chat.messages.push({
      role: 'assistant',
      content: '抱歉，我遇到了一些问题，无法回答您的问题。请稍后再试。',
      timestamp: Date.now()
    });
  } finally {
    isLoading.value = false;
  }
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substring(2);
};

// 模拟AI响应（实际项目中应该调用真实的AI API）
const generateAIResponse = (userMessage: string) => {
  // 简单的响应逻辑，实际项目中应替换为真实API调用
  if (userMessage.includes('你好') || userMessage.includes('嗨') || userMessage.includes('hi')) {
    return '你好！我是辰晓AI助手，有什么我可以帮助你的吗？';
  } else if (userMessage.includes('名字')) {
    return '我是辰晓AI助手，很高兴为您服务！';
  } else if (userMessage.includes('谢谢') || userMessage.includes('感谢')) {
    return '不客气！如果还有其他问题，随时可以问我。';
  } else if (userMessage.includes('能力') || userMessage.includes('做什么')) {
    return '我可以回答问题、提供信息、帮助编写代码、解释概念、提供建议等。有什么具体的问题我可以帮你解答吗？';
  } else {
    return `我已收到您的问题："${userMessage}"。\n\n这是一个很有趣的问题。在实际应用中，我会连接到强大的AI模型来提供准确的回答。目前这只是一个演示界面，所以我无法提供详细的回答。\n\n在真实的应用中，我可以：\n- 回答各种知识性问题\n- 提供编程帮助\n- 解释复杂概念\n- 生成创意内容\n- 提供建议和指导\n\n您可以继续提问来体验这个界面的交互方式。`;
  }
};
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(155, 155, 155, 0.5);
  border-radius: 20px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: rgba(155, 155, 155, 0.7);
}
</style>
